import psycopg2
from psycopg2 import OperationalError, ProgrammingError

# 数据库连接参数
dwr_prd_config_me = {
    "db_host": "192.168.88.128",  # 数据库主机地址
    "db_port": "15432",  # 数据库端口，默认5432
    "db_name": "dwr_prd",  # 数据库名称
    "db_user": "gaussdb",  # 用户名
    "db_password": "Gauss@123"  # 密码
}
dm_prd_config_me = {
    "db_host": "192.168.88.128",  # 数据库主机地址
    "db_port": "15432",  # 数据库端口，默认5432
    "db_name": "dm_prd",  # 数据库名称
    "db_user": "gaussdb",  # 用户名
    "db_password": "Gauss@123"  # 密码
}
dwr_prd_config = {
    "db_host": "10.81.31.78",  # 数据库主机地址
    "db_port": "8000",  # 数据库端口，默认5432
    "db_name": "dwr_prd",  # 数据库名称
    "db_user": "dbadmin",  # 用户名
    "db_password": "Huawei@dt.c0m"  # 密码
}
dm_prd_config = {
    "db_host": "10.81.31.78",  # 数据库主机地址
    "db_port": "8000",  # 数据库端口，默认5432
    "db_name": "dm_prd",  # 数据库名称
    "db_user": "dbadmin",  # 用户名
    "db_password": "Huawei@dt.c0m"  # 密码
}

def create_connection(db_host, db_port, db_name, db_user, db_password):
    """创建与高斯数据库的连接"""
    connection = None
    try:
        connection = psycopg2.connect(
            host=db_host,
            port=db_port,
            database=db_name,
            user=db_user,
            password=db_password,
            client_encoding='utf8'
        )
        print("成功连接到数据库")
    except OperationalError as e:
        print(f"连接错误: {e}")
    return connection



def execute_query(connection, query, params=None):
    """执行SQL查询（INSERT, UPDATE, DELETE）"""
    cursor = connection.cursor()
    try:
        # 添加参数验证
        if params is not None:
            # 检查参数数量是否匹配（根据具体SQL方言调整）
            placeholder_count = query.count('?')  # 对于某些数据库
            # 或者 placeholder_count = query.count('%s')  # 对于MySQL
            if len(params) != placeholder_count:
                raise ValueError(f"参数数量不匹配：期望{placeholder_count}个，实际{len(params)}个")
        if params:
            cursor.execute(query, params)
        else:
            cursor.execute(query)
        connection.commit()
        print("查询执行成功")
        return True
    except ProgrammingError as e:
        print(f"执行错误: {e}")
        connection.rollback()
        return False
    finally:
        cursor.close()


def fetch_data(connection, query, params=None):
    """执行查询并返回结果（SELECT）"""
    try:
        cursor = connection.cursor()
        result = None
        cursor.execute(query, params or ())
        result = cursor.fetchall()
        return result
    except ProgrammingError as e:
        print(f"查询错误: {e}")
        return None
    finally:
        cursor.close()
